package com.wu.capture.frame.view

import android.os.Build
import android.util.Log
import android.view.View
import android.view.WindowManager
import com.avsdk.*
import com.wkq.base.frame.mosby.delegate.MvpView
import com.wu.base.util.StatusBarUtil
import com.wu.capture.MainActivity
import com.wu.capture.application.VideoCaptureApplication
import com.wu.capture.util.PathUtil
import com.wu.capture.util.VideoCaptureConstant
import java.io.IOException


/**
 * @author wkq
 *
 * @date 2022年02月23日 15:14
 *
 *@des
 *
 */

class MainView(mActivity: MainActivity) : MvpView {

    var mActivity = mActivity

    var m_bViewStart = false


    //设置全屏
    fun processFullScreen() {
        StatusBarUtil.setTransparentForWindow(mActivity)
        StatusBarUtil.addTranslucentView(mActivity, 0)
        StatusBarUtil.setLightMode(mActivity)
        val lp: WindowManager.LayoutParams = mActivity.getWindow().getAttributes()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lp.layoutInDisplayCutoutMode =
                    WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        }
        mActivity.getWindow().setAttributes(lp)
        // 设置页面全屏显示
        val decorView: View = mActivity.getWindow().getDecorView()
        decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
    }

    var isStartRecord = false
    fun initView() {
        processFullScreen()
        initVideo()
        mActivity.binding.bt.setOnClickListener {
            var path = PathUtil.getPath(mActivity)
            var pathBytes = path!!.toByteArray();
            if (!isStartRecord) {
                isStartRecord = true
                mActivity.binding.bt.text = "点击结束录制"
                H264DecodeJni.getInstance().StartRecord(VideoCaptureApplication.initDecodeResult, pathBytes);
            } else {
                isStartRecord = false
                if (VideoCaptureApplication.initDecodeResult == 0) return@setOnClickListener
//               var file= File(path,""+System.currentTimeMillis())
//                file.createNewFile()
                H264DecodeJni.getInstance().StopRecord(VideoCaptureApplication.initDecodeResult)
                mActivity.binding.bt.text = "开始录制"

            }

        }
    }


    private fun initVideo() {
        //设置录制的横竖屏

        VideoCaptureApplication.videoCap!!.StartCapture(mActivity.binding.gLSurfaceView,
                VideoCaptureConstant.videoWidth,
                VideoCaptureConstant.videoHeight,
                false,
                object : AVCapCallBack {
                    override fun OnVideoCallBack(buf: ByteArray?, length: Int) {
                        onUnionVideoCallBack(buf, length, 0)
                    }


                    override fun OnAudioCallBack(buf: ByteArray?, length: Int) {
                    }
                })
        VideoCaptureApplication.videoCap!!.SetOrientation(0);
    }

    var UnionCallBackTimes = 0
    private fun onUnionVideoCallBack(buf: ByteArray?, length: Int, sourceType: Int) {
        try {
            UnionCallBackTimes++
            if (UnionCallBackTimes % 200 == 0) {
//                ToastShow("字节长度为 $length")
            }
            //格式转化
            val dealBtye: ByteArray
            //内置的 需要旋转
            dealBtye = if (sourceType == 0) {
                //旋转
                val yvbtye = ByteArray(length)
                //调用c的转
                H264DecodeJni.getInstance().NvToYuv(
                        0,
                        buf,
                        VideoCaptureConstant.videoHeight,
                        VideoCaptureConstant.videoWidth,
                        yvbtye
                )
                val rotateByte = ByteArray(length)
                H264DecodeJni.getInstance().RotateYuv(
                        yvbtye,
                        VideoCaptureConstant.videoHeight,
                        VideoCaptureConstant.videoWidth,
                        rotateByte,
                        3
                )
                rotateByte
            } else {
                val yvbtye = ByteArray(length)
                //调用c的转
                H264DecodeJni.getInstance().NvToYuv(
                        1,
                        buf,
                        VideoCaptureConstant.videoHeight,
                        VideoCaptureConstant.videoWidth,
                        yvbtye
                )
                yvbtye
            }

            //处理其他注册回调
            if (!m_bViewStart) {
                mActivity.binding.gLSurfaceView.setVideoSize(
                        VideoCaptureConstant.videoWidth,
                        VideoCaptureConstant.videoHeight,
                        VideoCaptureConstant.PIX_FMT_YUV420P
                )
                m_bViewStart = true
            }
            if (m_bViewStart) mActivity.binding.gLSurfaceView.addFrame(
                    VideoCaptureConstant.PIX_FMT_YUV420P,
                    dealBtye,
                    length
            )

            //处理录像和网络
            if (sourceType == 0) {
                processVideoStream(
                        dealBtye,
                        length,
                        VideoCaptureConstant.videoWidth,
                        VideoCaptureConstant.videoHeight
                )
            } else if (sourceType == 1) {
                processVideoStream(
                        dealBtye,
                        length,
                        VideoCaptureConstant.videoWidth,
                        VideoCaptureConstant.videoHeight
                )
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun processVideoStream(
            buf: ByteArray,
            length: Int,
            videoWidth: Int,
            videoHeight: Int
    ) {

        if (videoWidth != VideoCaptureApplication.previdewSize_Width || videoHeight != VideoCaptureApplication.getPrevidewSize_Height) {
            VideoCaptureApplication.previdewSize_Width = videoWidth
            VideoCaptureApplication.getPrevidewSize_Height = videoHeight
            if (VideoCaptureApplication.videoencBuffer != null) {
                VideoCaptureApplication.videoencBuffer = null
            }
            if (VideoCaptureApplication.videoEncode!!.IsEncodeOpen()) {
                VideoCaptureApplication.videoEncode!!.UnInitEncode()
            }
        }


        if (VideoCaptureApplication.videoencBuffer == null)
            VideoCaptureApplication.videoencBuffer = ByteArray(videoWidth * videoHeight * 2)



        if (!VideoCaptureApplication.videoEncode!!.IsEncodeOpen()) VideoCaptureApplication.videoEncode!!.InitEncode(
                videoWidth,
                videoHeight,
                VideoCaptureConstant.videoWidth * 200
        )
        if (!VideoCaptureApplication.videoEncode!!.IsEncodeOpen()) return

        //压缩码流
        var outlen = VideoCaptureApplication.videoEncode!!.EncodeVideo(
                buf,
                length,
                VideoCaptureApplication.videoencBuffer,
                videoWidth * videoHeight * 2
        );

        Log.e("长度:", outlen.toString())
        if (outlen > 0) {

            // 服务器传递视频数据
            if (VideoCaptureApplication.initDecodeResult > 0) {
                H264DecodeJni.getInstance().InputData(
                        VideoCaptureApplication.initDecodeResult,
                        0,
                        VideoCaptureApplication.videoencBuffer,
                        outlen
                )
            }

            if (VideoCaptureApplication.netCode >= 0) {
                HancNetJni.getInstance().HancSendEx(
                        VideoCaptureApplication.netCode,
                        2,
                        VideoCaptureApplication.videoencBuffer,
                        outlen
                )

            }
        }

    }


}